package com.controller;

import com.dao.UserMapper;
import com.model.User;
import com.util.EmailSendUtil;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 汪林
 * @date 2020/8/5 19:27
 */
@Controller
@RequestMapping("register")
public class RegisterController {
    @Autowired
    private EmailSendUtil emailSendUtil;
    @Autowired
    private UserMapper userMapper;

    //注册功能
    @RequestMapping(value = "register.do",produces = "application/json;charset=utf-8")
    @ResponseBody
    public int register(User user){
//        System.out.println("---------register()-----------"+user);
        //1.添加用户到数据库（未激活--原文密码--不能登录）
        int i = userMapper.insertSelective(user);
        System.err.println("添加成功"+i);
        //2.注册后向注册用户发送激活邮件
        emailSendUtil.sendMessage(user);
        return i;
    }
    //激活功能
    @RequestMapping("ActiveUser.do")
    public String ActiveServlet(HttpServletRequest request){
        System.out.println("-----------激活方法ActiveServlet（）----------");

        String registerEmail = request.getParameter("registerEmail");
        System.out.println(registerEmail);
        User user = userMapper.selectByEmail(registerEmail);
        //激活--将原文密码改变为密文密码
        //设置加密方式
        String algorithmName = "MD5";
        //设置待加密的原密码
        Object source = user.getPassword();
        //设置加盐方式(一般来说都是以用户名来加盐)
        Object salt = ByteSource.Util.bytes(user.getUsername());
        /* 加密次数 */
        int hashIterations = 1024;
        String newPassword = new SimpleHash(algorithmName, source, ByteSource.Util.bytes(salt), hashIterations).toHex();

        //将密文更新写入数据库
        user.setPassword(newPassword);
        userMapper.updateByPrimaryKeySelective(user);
        userMapper.insertIntoUserRoleByUserId(user.getUserid());
        return "registerSuccess";
    }
}
